package com.thti.mecool.client.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.base.ImageUpload;
import com.thti.mecool.client.command.send.plan.PlanSend;
import com.thti.mecool.client.model.biz.MessagesBizImpl;
import com.thti.mecool.client.model.biz.PlanBizImpl;
import com.thti.mecool.client.model.biz.TaskBizImpl;
import com.thti.mecool.client.model.po.PlanClient;
import com.thti.mecool.client.model.po.Task;
import com.thti.mecool.client.util.NetTool;
import com.thti.mecool.client.util.NetTool.NetProgress;
import com.thti.mecool.client.util.TimeUtil;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.ListWidget;
import com.thti.mecool.client.widget.ProgressDialogWidget;
import com.thti.mecool.client.widget.Toolbar;

public class TaskActivity extends BaseActivity {
	private Toolbar toolbar;
	// private Button SyncBtn;
	private Button Sync_upLoad;
	private Button Sync_cancel;
	private ListWidget doneTask;
	private TextView mecool_tabText;
	private ArrayList<TextView> tabtextlist = new ArrayList<TextView>();
	private ArrayList<ArrayList<Integer>> stat = new ArrayList<ArrayList<Integer>>();
	private ArrayList<String> listTag = new ArrayList<String>();
	private ArrayList<String> donelistTag = new ArrayList<String>();
	private ArrayList<ArrayList<HashMap<String, String>>> taskList = new ArrayList<ArrayList<HashMap<String, String>>>();
	private ArrayList<ArrayList<HashMap<String, String>>> donetaskList = new ArrayList<ArrayList<HashMap<String, String>>>();
	private ImageUpload imageUpload;
	private ProgressDialogWidget pd;
	private ListWidget lw;
	ArrayList<HashMap<String, String>> uploadTasks=new ArrayList<HashMap<String,String>>();
	MessagesBizImpl messagesBizImpl;
	private ArrayList<String> ProjectIds, PlanIds, StoreCodes, StoreNames,
			taskIds, taskNames;
	private ArrayList<String> doneProjectIds, donePlanIds, doneStoreCodes,
			doneStoreNames, donetaskIds, donetaskNames;
	private boolean echo;
	PlanBizImpl planBizImpl;
	TaskBizImpl taskBizImpl;
	private Runnable r = new Runnable() {
		@Override
		public void run() {
			if (getDataFlag(HandlerConstant.PlanCommand)) {
				initSql();
				if (pd.isShowing()) {
					pd.dismiss("获取到数据！");
				}
				messagesBizImpl.upAssign();
				removeDataFlag(HandlerConstant.PlanCommand);
				handler.removeCallbacks(r);
			}else if(getDataFlag(HandlerConstant.UploadImgCommand)){
				imageUpload.uploadImage(1,uploadTasks.size()==0?uploadAllTasks():uploadTasks);
				taskBizImpl.uploadTask("1",uploadTasks.size()==0?uploadAllTasks():uploadTasks);
				pd.setProgress(100);
				removeDataFlag(HandlerConstant.UploadImgCommand);
				handler.removeCallbacks(r);
				handler.post(r);
			}else if(getDataFlag(HandlerConstant.UploadCurCommand)){
				if(pd.isShowing())
					pd.dismiss("上传成功！");
				taskBizImpl.uploadTask("2",uploadTasks.size()==0?uploadAllTasks():uploadTasks);
				handler.removeCallbacks(r);
				removeDataFlag(HandlerConstant.UploadCurCommand);
				initSql();
				doneTask.donelistRefurbish();
			}else {
				if(getDataFlag(HandlerConstant.CommandFail)){
					removeDataFlag(HandlerConstant.CommandFail);
					if(pd.isShowing())
						pd.dismiss();
					if(getCurrentMesg().getContent()!=null)
						Util.sendToast(TaskActivity.this, getCurrentMesg().getContent());
					else
					Util.sendToast(TaskActivity.this, "数据获取异常！");
				}else
				handler.postDelayed(r, 1000);
			}
		}
	};
	private Handler handler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Cache.add(this);
		this.noTitle();
		setContentView(R.layout.mecool_taskmanage);
		ProjectIds = new ArrayList<String>();
		PlanIds = new ArrayList<String>();
		StoreCodes = new ArrayList<String>();
		StoreNames = new ArrayList<String>();
		taskIds = new ArrayList<String>();
		taskNames = new ArrayList<String>();

		doneProjectIds = new ArrayList<String>();
		donePlanIds = new ArrayList<String>();
		doneStoreCodes = new ArrayList<String>();
		doneStoreNames = new ArrayList<String>();
		donetaskIds = new ArrayList<String>();
		donetaskNames = new ArrayList<String>();


		handler = new Handler();
		messagesBizImpl=new MessagesBizImpl(this);
		pd = new ProgressDialogWidget(this,false);
		if(messagesBizImpl.findAssign()){
			PlanSend.getPlan(getCurrentUser().getLoginName(),TimeUtil.dateToYear());
			pd.show();
			pd.setDismissTime(45);
			handler.post(r);
		}
		// undoneListView=new ListWidget(activity, taskList, listTag, stat);
		initSql();

		TabHost mecool_taskHost = (TabHost) findViewById(R.id.mecool_taskHost);
		mecool_taskHost.setup();
		mecool_taskHost.addTab(mecool_taskHost.newTabSpec("undonetask")
				.setIndicator(createTab("待办任务")).setContent(R.id.undone_task));
		tabtextlist.get(0).setTextColor(Color.WHITE);
		mecool_taskHost.addTab(mecool_taskHost.newTabSpec("donetask")
				.setIndicator(createTab("已完成任务"))
				.setContent(R.id.mecool_done_task));
		mecool_taskHost.setOnTabChangedListener(new myOnTabChangedListener());
		Sync_upLoad = (Button) findViewById(R.id.mecool_Sync_upload);
		Sync_cancel = (Button) findViewById(R.id.mecool_Sync_cancel);
		Button mecool_SyncBtn = (Button) findViewById(R.id.mecool_SyncBtn);
		mecool_SyncBtn.setOnClickListener(MyOnClickListener);
		Sync_cancel.setOnClickListener(new TaskOnClickListener());

//		if (!getSharedPreferences("Setting", 0)
//				.getBoolean("AutoRefresh", false)) {
//		if(true){
	
//			PlanSend.getPlan(getCurrentUser().getLoginName(), "2012-07-16");
//		 }
	}

	private void initSql() {
		clearList();
		planBizImpl = new PlanBizImpl(this);
		// List<PlanClient> PlanClients =
		List<PlanClient> PlanClients = planBizImpl.findByType(TimeUtil.dateToYear());
//		List<PlanClient> PlanClients = planBizImpl.findByType("2012-07-16");

		for (PlanClient pc : PlanClients) {
			if (pc != null) {
				taskBizImpl = new TaskBizImpl(this);
				if (pc.getPlanId() != null) {
//					tasks.addAll
					List<Task> tasks=taskBizImpl.findByprojectId(pc.getPlanId(),
							pc.getType(), 0,
							String.valueOf(getCurrentUser().getId()));
					System.out.println("tasks   :   " + tasks);
					List<Task> donetasks=taskBizImpl.findByprojectId(
							pc.getPlanId(), pc.getType(), 1,
							String.valueOf(getCurrentUser().getId()));
					if (tasks != null) {
						foreachTask(tasks, pc.getType(), pc.getPlanId());
						if (lw == null)
							lw = new ListWidget(TaskActivity.this, taskList,
									listTag);
						else {
							// lw.listExtra(listTag);
							lw.listRefurbish();
						}
						lw.setPlanIdAndProjectIds(PlanIds, ProjectIds,
								StoreCodes, StoreNames, taskIds, taskNames);
					}
					if (donetasks != null) {
						foreachDoneTask(donetasks, pc.getType(), pc.getPlanId());
					}
				}
			}
		}
		if (doneTask == null)
			doneTask = new ListWidget(TaskActivity.this,
					donetaskList, donelistTag, stat);
		else {
			// doneTask.donelistExtra(donelistTag);
			doneTask.setStat(stat);
			doneTask.donelistRefurbish();
		}
	}

	private void clearList() {
		taskList.clear();
		listTag.clear();
		PlanIds.clear();
		ProjectIds.clear();
		StoreCodes.clear();
		StoreNames.clear();
		taskIds.clear();
		taskNames.clear();

		donetaskList.clear();
		donelistTag.clear();
		donePlanIds.clear();
		doneProjectIds.clear();
		doneStoreCodes.clear();
		doneStoreNames.clear();
		donetaskIds.clear();
		donetaskNames.clear();
	}
	
	private void foreachTask(List<Task> tasks, String type, String planId) {
		for (Task task : tasks) {
			ArrayList<HashMap<String, String>> proj = new ArrayList<HashMap<String, String>>();
			HashMap<String, String> t = new HashMap<String, String>();
			t.put("name", task.getTaskName());
			t.put("time", task.getStartTime() + " - " + task.getEndTime());
			t.put("addr", task.getStoreName());
			t.put("planId", task.getPlanId());
			t.put("projectId", task.getProjectId());
			t.put("taskId", task.getTaskId());
			
			t.put("isType", type);
			proj.add(t);
			PlanIds.add(planId);
			listTag.add(task.getProjectName());
			taskList.add(proj);
			taskIds.add(task.getTaskId());
			ProjectIds.add(task.getProjectId());
			StoreCodes.add(task.getStoreId());
			StoreNames.add(task.getStoreName());
			taskNames.add(task.getTaskName());
		}
	}

	private void foreachDoneTask(List<Task> tasks, String type, String planId) {
		for (Task task : tasks) {
			ArrayList<HashMap<String, String>> proj = new ArrayList<HashMap<String, String>>();
			HashMap<String, String> t = new HashMap<String, String>();
			t.put("name", task.getTaskName());
			t.put("time", task.getStartTime() + " - " + task.getEndTime());
			t.put("addr", task.getStoreName());
			t.put("planId", task.getPlanId());
			t.put("projectId", task.getProjectId());
			t.put("taskId", task.getTaskId());
			t.put("isType", type);
			proj.add(t);
			donelistTag.add(task.getProjectName());
			donetaskList.add(proj);
			donetaskIds.add(task.getTaskId());
			doneProjectIds.add(task.getProjectId());
			doneStoreCodes.add(task.getStoreId());
			donePlanIds.add(task.getPlanId());
			doneStoreNames.add(task.getStoreName());
			donetaskNames.add(task.getTaskName());

			ArrayList<Integer> curstat = new ArrayList<Integer>();
			curstat.add(0);
			curstat.add(Integer.parseInt(task.getIsUpload()));
			curstat.add(0);
			stat.add(curstat);
		}
	}

	class TaskOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.mecool_SyncBtn:
				// SyncBtn.setVisibility(8);
				Sync_upLoad.setVisibility(0);
				Sync_cancel.setVisibility(0);
				BaseActivity.IsSyncEcho = false;
				doneTask.listRefurbish();
				break;
			case R.id.mecool_Sync_cancel:
				// SyncBtn.setVisibility(0);
				Sync_upLoad.setVisibility(8);
				Sync_cancel.setVisibility(8);
				BaseActivity.IsSyncEcho = true;
				doneTask.listRefurbish();
				break;
			default:
				break;
			}
		}
	}

	OnClickListener MyOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.mecool_toolbar_rightbtn:
				Intent i = new Intent(TaskActivity.this,
						TaskdoneDetailActivity.class);
				Bundle data = new Bundle();
				data.putSerializable("Tasklist", taskList);
				data.putSerializable("ListTag", listTag);
				i.putExtras(data);
				startActivity(i);
				break;
			case R.id.mecool_SyncBtn:
				if(donetaskList.size()>0){
				imageUpload=new ImageUpload(TaskActivity.this);
				pd.upProgress();
				Thread t=new Thread(){
					@Override
					public void run() {
						NetTool.setNetProgress(netProgress);
						imageUpload.uploadImage(0,uploadTasks.size()==0?uploadAllTasks():uploadTasks);
					};
				};
				t.start();
				pd.show();
				Util.sendToast(TaskActivity.this, "正在上传！");
				handler.post(r);}
				else{
					Util.sendToast(TaskActivity.this,"当前没有已完成任务！");
				}
				break;
			default:
				finish();
				break;
			}
		}
	};
	NetProgress netProgress=new NetProgress() {
		
		@Override
		public void progress(int progress) {
			if(progress<100)
			pd.setProgress(progress);
		}
	};
	public ArrayList<HashMap<String,String>> uploadAllTasks(){
		ArrayList<HashMap<String, String>> list=new ArrayList<HashMap<String,String>>();
		int i=0;
		for(String s:donetaskIds){
			if(taskBizImpl.findUpload(donePlanIds.get(i), s)!=2){
			HashMap<String, String> uploadtask=new HashMap<String, String>();
			uploadtask.put("planId", donePlanIds.get(i));
			uploadtask.put("taskId", s);
			list.add(uploadtask);
			}
			i++;
		}
		return list;
	}
	class myOnTabChangedListener implements OnTabChangeListener {
		@Override
		public void onTabChanged(String tabId) {
			FrameLayout fl = (FrameLayout) findViewById(R.id.mecool_SyncBtn_framelayout);
			for (TextView tv : tabtextlist) {
				if (tv.isSelected()) {
					tv.setTextColor(Color.WHITE);
				} else {
					tv.setTextColor(Color.GRAY);
				}
			}
			if (tabId.equals("donetask")) {
				toolbar.setimage(Toolbar.right_btn,
						R.drawable.mecool_uncompleted_task_mark);
				Toolbar.hideRightButton();
				fl.setVisibility(0);
			} else {
				// toolbar.setimage(toolbar.right_btn, R.drawable.ic_launcher);
				toolbar.showRightButton();
				fl.setVisibility(8);
			}
		}
	}

	/**
	 * 自定义Tab标签的背景内容等
	 * 
	 * @param tabText
	 * @return
	 */
	public View createTab(String tabText) {
		View view = LayoutInflater.from(this).inflate(
				R.layout.mecool_task_tabindicator, null);
		mecool_tabText = (TextView) view.findViewById(R.id.mecool_tabText);
		mecool_tabText.setText(tabText);
		tabtextlist.add(mecool_tabText);
		return view;
	}

	@Override
	protected void onDestroy() {
		IsSyncEcho = true;
		if (getDataFlag(HandlerConstant.PlanCommand)) {
			removeDataFlag(HandlerConstant.PlanCommand);
		}
		super.onDestroy();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		echo = intent.getBooleanExtra("echo", false);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (echo) {
			initSql();
			lw.listRefurbish();
			doneTask.donelistRefurbish();
		} else {
			toolbar = new Toolbar(this);
			Toolbar.left_btn.setOnClickListener(MyOnClickListener);
			Toolbar.right_btn.setOnClickListener(MyOnClickListener);
			toolbar.setimage(Toolbar.left_btn, R.drawable.mecool_go_back);
			toolbar.setToolbarCentreText("任务管理");
			toolbar.setimage(Toolbar.right_btn,
					R.drawable.mecool_uncompleted_task_mark);
		}
	}
}
